package com.base.cn.platform.os.controller.course.live;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.CcLiveUtils;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.TT.TTServiceUtils;
import com.base.cn.platform.os.common.utils.http.HttpUtil;
import com.base.cn.platform.os.common.utils.ke96.Ke96ServiceUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.entity.course.material.CouMaterial;
import com.base.cn.platform.os.entity.course.open.CourseOpen;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.entity.user.user.UserCondition;
import com.base.cn.platform.os.service.course.material.CouMaterialService;
import com.base.cn.platform.os.service.course.open.CourseOpenService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.github.pagehelper.PageInfo;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 创建96K直播间Controller
 *
 * @author s.li
 * @create 2018-05-03-18:53
 */
@Controller
@RequestMapping("/admin/liveToV/create")
public class LiveV96KCreateController extends AdminBaseController {
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private Ke96ServiceUtils ke96ServiceUtils;
    @Autowired
    private TTServiceUtils ttServiceUtils;
    @Autowired
    private SysTeacherService sysTeacherService;
    @Autowired
    private CourseOpenService courseOpenService;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CouMaterialService couMaterialService;


    /**
     * 初始化创建直播间页面
     * @return 操作页面
     */
    @RequestMapping("/initCCCreateLivePage")
    public String initCCCreateLivePage(Model model,
                                       @RequestParam(value = "liveBilling",required = false,defaultValue = "0") Integer liveBilling) throws IOException {
        if(liveBilling==0){
            return resultPage("/course/live/cc-create-live");
        }else{
            return resultPage("/course/live/create-small-class-live");
        }
    }
    /**
     * 初始化上传音频或视频页面
     * @param type 类型，1视频，2音频
     * @return 操作页面
     */
    @RequestMapping("/initVideoUploadPage")
    public String initVideoUploadPage(Model model,
                                      @RequestParam("type") int type){
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.V96K);
        model.addAttribute("type",type);
        model.addAttribute("configMap",configMap);
        return resultPage("/course/live/upload-video");
    }

    /**
     * 创建直播间

     * @return Map<String,Object>
     */
    @RequestMapping("/saveCcLiveData")
    @ResponseBody
    public Map<String,Object> saveCCLiveData(
            @RequestParam("name") String name,
            @RequestParam("desc") String desc,
            @RequestParam("templatetype") String templatetype,
            @RequestParam("maxaudiencenum") String maxaudiencenum,
            @RequestParam("start_time") String start_time,
            @RequestParam("end_time") String end_time,
            @RequestParam(value = "barrage", required = false, defaultValue = "") String barrage,
            @RequestParam(value = "foreignpublish", required = false, defaultValue = "") String foreignpublish,
            @RequestParam(value = "manuallyrecordmode", required = false, defaultValue = "") String manuallyrecordmode,
            @RequestParam(value = "authtype", required = false, defaultValue = "") String authtype,@RequestParam(value = "openchatmanage", required = false, defaultValue = "") String openchatmanage,
            @RequestParam(value = "documentdisplaymode", required = false, defaultValue = "1") String documentdisplaymode,
            @RequestParam(value = "showusercount", required = false, defaultValue = "") String showusercount
    ) throws Exception{

                if(StringUtils.isEmpty(name)){
                    return ResultUtil.ERROR("直播间名称不能为空");
                }
                if(name.trim().length()>40){
                    return ResultUtil.ERROR("直播间名称不能大于40个字符");
                }
                if(StringUtils.isEmpty(desc)){
                    return ResultUtil.ERROR("直播间描述不能为空");
                }
                if(desc.trim().length()>5000){
                    return ResultUtil.ERROR("直播间描述不能大于5000个字符");
                }
                if(StringUtils.isEmpty(start_time)){
                    return ResultUtil.ERROR("请选择直播开始时间");
                }
                if(StringUtils.isEmpty(end_time)){
                    return ResultUtil.ERROR("请选择直播结束时间");
                }
                Date startTime = DateUtils.parseDate(start_time, "yyyy-MM-dd HH:mm:ss");
                if (!startTime.after(new Date())) {
                    return ResultUtil.ERROR("直播开始时间要大于当前时间");
                }
                Date endTime = DateUtils.parseDate(end_time, new String[]{"yyyy-MM-dd HH:mm:ss"});
                if (startTime.after(endTime)) {
                    return ResultUtil.ERROR("直播结束时间要大于开始时间");
                }
                Map <String,String> data = new HashMap<>();
                data.put("name",name);
                data.put("desc",desc);
                data.put("templatetype",templatetype);
                data.put("maxaudiencenum",maxaudiencenum);
                data.put("publisherpass",StringUtils.generatingLotNumber()+"1");
                data.put("assistantpass",StringUtils.generatingLotNumber()+"2");
                data.put("livestarttime",start_time);
                data.put("manuallyrecordmode","0");
                data.put("documentdisplaymode",documentdisplaymode);
                if(StringUtils.isNotEmpty(showusercount)&&showusercount.equals("on")){
                    data.put("showusercount","1");
                }
                //是否免密验证
                data.put("authtype","1");
                data.put("playpass",StringUtils.generatingLotNumber()+"3");
                if(StringUtils.isNotEmpty(authtype)&&authtype.equals("on")){
                    data.put("authtype","2");
                    data.put("playpass",null);
                }
                if(StringUtils.isNotEmpty(barrage)&&barrage.equals("on")){
                    data.put("barrage","1");
                }
            if(StringUtils.isNotEmpty(openchatmanage)&&openchatmanage.equals("on")){
                data.put("openchatmanage","1");
            }
                if(StringUtils.isNotEmpty(foreignpublish)&&foreignpublish.equals("on")){
                    data.put("foreignpublish","1");
                }
                if(StringUtils.isNotEmpty(manuallyrecordmode)&&manuallyrecordmode.equals("on")){
                    data.put("manuallyrecordmode","0");
                }
                if(StringUtils.isEmpty(manuallyrecordmode) || manuallyrecordmode.equals("off")){
                    data.put("manuallyrecordmode","1");
                }
                String url = "http://api.csslcloud.net/api/room/create";
                Map<String, Object> resultMaps  = ke96ServiceUtils.demandLive(url,data);

                if(resultMaps.get("result").equals("OK")){
                    HashMap<String, String> mapTo = new HashMap<>();
                    Map roomMap = (Map) resultMaps.get("room");
                    mapTo.put("start_time",start_time);
                    mapTo.put("end_time",end_time);
                    mapTo.put("room_id",roomMap.get("id").toString());
                    mapTo.put("sign",roomMap.get("id").toString());
                    mapTo.put("admin_code",data.get("assistantpass"));
                    mapTo.put("teacher_code",data.get("publisherpass"));
                    mapTo.put("student_code",data.get("playpass"));

                    //获取直播间地址
                    url = "http://api.csslcloud.net/api/room/code";
                    Map<String,Object> params = new HashMap<>();
                    params.put("roomid",roomMap.get("id").toString());
                    Map<String, Object> roomInfoMap = ke96ServiceUtils.demandLive(url,params);
                    if(roomInfoMap.get("result").equals("OK")){
                        mapTo.put("studentUrl",roomInfoMap.get("viewUrl").toString());//学员地址
                        mapTo.put("teacherUrl",roomInfoMap.get("clientLoginUrl").toString());//讲师地址
                        mapTo.put("adminUrl",roomInfoMap.get("assistantLoginUrl").toString());//助教地址
                    }
                    return ResultUtil.SUCCESS("直播间数据创建成功",mapTo);
                }
        return ResultUtil.ERROR("创建失败",resultMaps.get("reason"));

    }

    //格式直播时间
    private String formatDate(String time) {
        Long start = (Long.valueOf(time) * 1000);
        Date startDate = new Date(start);
        return DateUtils.format(startDate,"yyyy-MM-dd HH:mm:ss");
    }


    /*******************小班课********************/

    /**
     * 创建小班课直播间
     * @return Map<String,Object>
     */
    @RequestMapping("/saveCcLiveSmallData")
    @ResponseBody
    public Map<String,Object> saveCcLiveSmallData(
                                @RequestParam("name") String name,
                                @RequestParam("desc") String desc,
                                @RequestParam("templatetype") String templatetype,
                                @RequestParam("max_users") Integer max_users,
                                @RequestParam("start_time") String start_time,
                                @RequestParam("end_time") String end_time,
                                @RequestParam(value = "talkerAuthtype", required = false, defaultValue = "") String talkerAuthtype,
                                @RequestParam(value = "manuallyrecordmode", required = false, defaultValue = "") String manuallyrecordmode,
                                @RequestParam(value = "assist_switch", required = false, defaultValue = "") String assist_switch) throws Exception{

        if(StringUtils.isEmpty(name)){
            return ResultUtil.ERROR("直播间名称不能为空");
        }
        if(name.trim().length()>40){
            return ResultUtil.ERROR("直播间名称不能大于40个字符");
        }
        if(StringUtils.isEmpty(desc)){
            return ResultUtil.ERROR("直播间描述不能为空");
        }
        if(desc.trim().length()>10000){
            return ResultUtil.ERROR("直播间描述不能大于10000个字符");
        }
        if(StringUtils.isEmpty(start_time)){
            return ResultUtil.ERROR("请选择直播开始时间");
        }
        if(StringUtils.isEmpty(end_time)){
            return ResultUtil.ERROR("请选择直播结束时间");
        }
        Date startTime = DateUtils.parseDate(start_time, new String[]{"yyyy-MM-dd HH:mm:ss"});
        if (!startTime.after(new Date())) {
            return ResultUtil.ERROR("直播开始时间要大于当前时间");
        }
        Date endTime = DateUtils.parseDate(end_time, new String[]{"yyyy-MM-dd HH:mm:ss"});
        if (startTime.after(endTime)) {
            return ResultUtil.ERROR("直播结束时间要大于开始时间");
        }

        Map <String,String> data = new HashMap<>();
        data.put("name",name);
        data.put("desc",desc);
        data.put("templatetype",templatetype);
        data.put("room_type","2");
        data.put("screen_lock","0");
        data.put("helper_switch","1");
        if(StringUtils.isNotEmpty(manuallyrecordmode)&&manuallyrecordmode.equals("on")){
            data.put("manual_record","0");
        }
        if(StringUtils.isEmpty(manuallyrecordmode) || manuallyrecordmode.equals("off")){
            data.put("manual_record","1");
        }
        if(max_users>0){
            data.put("max_streams",(max_users+1)+"");
        }
        String publisherpass = StringUtils.generatingLotNumber() + "1";
        String assist_pass = StringUtils.generatingLotNumber() + "2";
        String talker_pass = StringUtils.generatingLotNumber() + "3";

        if(StringUtils.isNotEmpty(assist_switch)&&assist_switch.equals("on")){
            data.put("assist_switch","1");
            data.put("assist_pass",assist_pass);
        }
        //播放认证
        //讲师
        data.put("publisherpass",publisherpass);

        //学生
        if(StringUtils.isNotEmpty(talkerAuthtype)&&talkerAuthtype.equals("on")){//免密认证
            data.put("talker_authtype","2");
            talker_pass = null;
            //旁听认证
            data.put("audience_authtype","2");        //回放认证方式
            data.put("viewer_authtype","2");

        }
        if(StringUtils.isEmpty(talkerAuthtype) || talkerAuthtype.equals("off")){//密码
            data.put("talker_authtype","1");
            data.put("talker_pass",talker_pass);
            //旁听认证
            data.put("audience_authtype","1");
            data.put("audience_pass",talker_pass);
            //回放认证方式
            data.put("viewer_authtype","1");
            data.put("viewer_pass",talker_pass);
        }
        //隐身者
        data.put("inspector_authtype","1");
        data.put("inspector_pass",assist_pass+"_a");

        data.put("ppt_support","true");
        data.put("schedule_switch","1");
        data.put("schedule_live_start",start_time);
        data.put("schedule_live_end",end_time);
        //创建直播间
        Map<String, Object> ccLiveData = ke96ServiceUtils.createCcSmallLiveData(data);
        if(!ResultUtil.getSuccess(ccLiveData)){
            return  ccLiveData;
        }

        Map<String, Object> mapTo = (Map<String, Object>) ResultUtil.getEntity(ccLiveData);
        mapTo.put("start_time",start_time);
        mapTo.put("end_time",end_time);
        mapTo.put("admin_code",assist_pass);
        mapTo.put("teacher_code",publisherpass);
        mapTo.put("student_code",talker_pass);

        //获取直播间信息
        Map<String, Object> smallLiveInfoData = ke96ServiceUtils.getCcSmallLiveInfoData(mapTo.get("room_id").toString());
        if(!ResultUtil.getSuccess(smallLiveInfoData)){
            return  smallLiveInfoData;
        }
        Map<String,Object> smallInfoMap = (Map<String, Object>) ResultUtil.getEntity(smallLiveInfoData);
        String studentUrl = smallInfoMap.get("audience_url").toString();
        String _studentUrl = studentUrl.substring(0,studentUrl.indexOf("?"));
        mapTo.put("studentUrl","https://livec2.96koo.net/api/newindex/talker/?"+studentUrl.substring(_studentUrl.length()+1,studentUrl.length()));//学员地址
        String teacherUrl = smallInfoMap.get("presenter_url").toString();
        String _teacherUrl = teacherUrl.substring(0,teacherUrl.indexOf("?"));
        mapTo.put("teacherUrl","https://livec2.96koo.net/api/newindex/presenter/?"+teacherUrl.substring(_teacherUrl.length()+1,teacherUrl.length()));//讲师地址
        String adminUrl = smallInfoMap.get("assist_url").toString();
        String _adminUrl = adminUrl.substring(0,adminUrl.indexOf("?"));
        mapTo.put("adminUrl","https://livec2.96koo.net/api/newindex/assistant/?"+adminUrl.substring(_adminUrl.length()+1,adminUrl.length()));//助教地址


        return ccLiveData;
    }

    /**
     * 获取进入直播间参数
     * @param roomid
     * @param type
     * @param selectType
     * @param name
     * @param couMaterialId
     * @param courseOpenId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLiveParam")
    @ResponseBody
    public Map<String, Object> getLiveParam(@RequestParam(value = "roomId", required = false) String roomid,
                                            @RequestParam("type") String type,
                                            @RequestParam("selectType") String selectType,
                                            @RequestParam(value = "name", required = false) String name,
                                            @RequestParam(value = "couMaterialId", required = false) BigDecimal couMaterialId,
                                            @RequestParam(value = "courseOpenId", required = false) BigDecimal courseOpenId) throws Exception {
        Map param = new HashMap();
        param.put("role", type);
        if ("indexLive".equals(selectType)) {
            Map<String, Object> materialMap = couMaterialService.findMaterialById(couMaterialId, false, true);
            param.put("classId", materialMap.get("roomId"));
            if ("1".equals(type)) {
                param.put("classId", materialMap.get("roomId"));
                Map teacherMap = (Map) materialMap.get("teacher");
                param.put("nickName", teacherMap.get("teacherName"));
                param.put("uuid", teacherMap.get("id").toString());
                Map imageMap = (Map) teacherMap.get("imageMap");
                Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                param.put("avatar", pcUrlMap.get("large"));
            } else if ("2".equals(type)) {
                if (StringUtils.isEmpty(materialMap.get("assistantId")) || "0".equals(materialMap.get("assistantId").toString())) {
                    return ResultUtil.ERROR("该直播间未设置助教老师");
                } else {
                    Map<String, Object> teacherMap = sysTeacherService.findSysTeacherById(new BigDecimal(materialMap.get("assistantId").toString()), false, false, false, false, false);
                    param.put("nickName", teacherMap.get("teacherName"));
                    param.put("uuid", teacherMap.get("id").toString());
                    Map imageMap = (Map) teacherMap.get("imageMap");
                    Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                    param.put("avatar", pcUrlMap.get("large"));
                }
            }
        } else if ("courseOpen".equals(selectType)) {
            //免费直播
            Map<String, Object> courseOpenmMap = courseOpenService.findCourseOpenById(courseOpenId, false, true, false);
            param.put("classId", courseOpenmMap.get("roomId"));
            if ("1".equals(type)) {  //老师
                Map teacherMap = (Map) courseOpenmMap.get("teacher");
                param.put("uuid", teacherMap.get("id").toString());
                param.put("nickName", teacherMap.get("teacherName"));
                Map imageMap = (Map) teacherMap.get("imageMap");
                Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                param.put("avatar", pcUrlMap.get("large"));
            } else if ("2".equals(type)) { //助教
                if (StringUtils.isEmpty(courseOpenmMap.get("tutorOne")) || "0".equals(courseOpenmMap.get("tutorOne").toString())) {
                    return ResultUtil.ERROR("该直播间未设置助教老师");
                } else {
                    Map<String, Object> teacherMap = sysTeacherService.findSysTeacherById(new BigDecimal(courseOpenmMap.get("tutorOne").toString()), false, false, false, false, false);
                    param.put("nickName", teacherMap.get("teacherName"));
                    param.put("uuid", teacherMap.get("id").toString());
                    Map imageMap = (Map) teacherMap.get("imageMap");
                    Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                    param.put("avatar", pcUrlMap.get("large"));
                }
            }
        } else {
            CourseOpen courseOpen = courseOpenService.findCourseOpenBySql("roomId = " + roomid);
            CouMaterial couMaterial = couMaterialService.findCouMaterialBySql("roomId = " + roomid);
            String liveType = "courseOpen";
            if (ObjectUtils.isEmpty(courseOpen)) {
                liveType = "couMaterial";
            }
            if ("couMaterial".equals(liveType)) {
                Map<String, Object> materialMap = couMaterialService.findMaterialById(couMaterial.getId(), false, true);
                param.put("classId", materialMap.get("roomId"));
                if ("1".equals(type)) {
                    param.put("classId", materialMap.get("roomId"));
                    Map teacherMap = (Map) materialMap.get("teacher");
                    param.put("nickName", teacherMap.get("teacherName"));
                    param.put("uuid", teacherMap.get("id").toString());
                    Map imageMap = (Map) teacherMap.get("imageMap");
                    Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                    param.put("avatar", pcUrlMap.get("large"));
                } else if ("2".equals(type)) {
                    if (StringUtils.isEmpty(materialMap.get("assistantId")) || "0".equals(materialMap.get("assistantId").toString())) {
                        return ResultUtil.ERROR("该直播间未设置助教老师");
                    } else {
                        Map<String, Object> teacherMap = sysTeacherService.findSysTeacherById(new BigDecimal(materialMap.get("assistantId").toString()), false, false, false, false, false);
                        param.put("nickName", teacherMap.get("teacherName"));
                        param.put("uuid", teacherMap.get("id").toString());
                        Map imageMap = (Map) teacherMap.get("imageMap");
                        Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                        param.put("avatar", pcUrlMap.get("large"));
                    }
                }
            } else {
                //免费直播
                Map<String, Object> courseOpenmMap = courseOpenService.findCourseOpenById(courseOpen.getId(), false, true, false);
                param.put("classId", courseOpenmMap.get("roomId"));
                if ("1".equals(type)) {  //老师
                    Map teacherMap = (Map) courseOpenmMap.get("teacher");
                    param.put("uuid", teacherMap.get("id").toString());
                    param.put("nickName", teacherMap.get("teacherName"));
                    Map imageMap = (Map) teacherMap.get("imageMap");
                    Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                    param.put("avatar", pcUrlMap.get("large"));
                } else if ("2".equals(type)) { //助教
                    if (StringUtils.isEmpty(courseOpenmMap.get("tutorOne")) || "0".equals(courseOpenmMap.get("tutorOne").toString())) {
                        return ResultUtil.ERROR("该直播间未设置助教老师");
                    } else {
                        Map<String, Object> teacherMap = sysTeacherService.findSysTeacherById(new BigDecimal(courseOpenmMap.get("tutorOne").toString()), false, false, false, false, false);
                        param.put("nickName", teacherMap.get("teacherName"));
                        param.put("uuid", teacherMap.get("id").toString());
                        Map imageMap = (Map) teacherMap.get("imageMap");
                        Map pcUrlMap = (Map) imageMap.get("pcUrlMap");
                        param.put("avatar", pcUrlMap.get("large"));
                    }
                }
            }
        }
        if ("3".equals(type)) { //学生
            UserCondition user = new UserCondition();
            user.setMobile(name);
            PageInfo<CusUser> cusUserList = cusUserService.findUserListPage(user, 1, 1);
            if (cusUserList.getList().size() == 1) {
                CusUser cusUser = (CusUser) cusUserList.getList().get(0);
                param.put("uuid", cusUser.getId().toString());
                param.put("nickName", cusUser.getNickname());
                param.put("avatar", cusUser.getAvatar());
            } else {
                return ResultUtil.ERROR("没有该学生", null);
            }
        }
        return ttServiceUtils.getLiveParam(param);
    }

    /**
     * 跳转直播
     * @param url
     * @param request
     * @return
     */
    @RequestMapping("/toLiveIframe")
    public String toLiveIframe(@RequestParam("url")String url, HttpServletRequest request){
        request.setAttribute("url",url);
        return resultPage("/course/live/iframe-live");
    }
}
